import React, { useCallback, useState, forwardRef, useImperativeHandle, ForwardedRef } from 'react';
import {
  editLabelName,
  deleteLabelName,
  SearchLabelManager,
  addLabelName,
  ITag,
} from '../../../../designer/service';
import moment from 'moment'
import { message, Popconfirm } from 'antd';
import cn from 'classnames';
import { InbizIcon } from '@inbiz/utils';
import { useEffect } from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { TextWidget, getMessage } from '@inbiz/react';

// import { ITag } from './AdvancedSearch/Detail';

interface Props {
  edit?: boolean;
  tagType?: string; // Type=1文件，Type=2文件夹
  layout?: 'vertical' | 'horizontal';
  // isDMS?: boolean
  ModuleName: string;
  // tagList?: any[];
  // $tagList: (value: React.SetStateAction<ITag[]>) => void
  onItemPress?: (labelID: string, item: any) => void;
}

export type ISearchTagRef = {
  save: (data: string) => void;
};
// 我的搜索标签（文件、文件夹高级搜索打的标签）
const MySearchTag = forwardRef((props: Props, ref: ForwardedRef<ISearchTagRef>) => {
  // edit为true,可编辑、删除操作【高级搜索里面的标签，Type=1文件，Type=2文件夹】
  const [tagList, $tagList] = useState<ITag[]>([]);

  useEffect(() => {
    getList(props.ModuleName);
  }, [props.ModuleName]);

  const getList = useCallback(
    (ModuleName) => {
      SearchLabelManager(ModuleName).then((res) => {
        $tagList(res);
      });
    },
    [props.ModuleName],
  );
  useImperativeHandle(
    ref,
    () => ({
      save: (LabelValue: string) => {
        addLabelName({
          LabelName: `${getMessage('SearchEngine.newLabel')}${tagList.length + 1}`,
          LabelValue,
          ModuleName: props.ModuleName,
        }).then((e) => {
          if (e.Code === 0) {
            message.success(getMessage('SearchEngine.newSuccessfully'));
          } else {
            message.error(getMessage('SearchEngine.saveLableError'));
          }
          getList(props.ModuleName);
        });
      },
    }),
    [props.tagType, tagList, props.ModuleName],
  );

  const { edit, tagType, layout = 'horizontal', onItemPress } = props;
  const [editId, $editId] = useState(null); // 状态

  // 编辑标签
  const onEdit = (id: any) => {
    $editId(id);
  };

  // 删除标签
  const confirm = async (data: any) => {
    await deleteLabelName(data.Id).then(() => {
      // getTagList()
      $tagList((list) => {
        const newList = [...list];
        const index = newList.findIndex((item) => item.Id == data.Id);
        newList.splice(index, 1);
        return newList;
      });
    });
  };

  const cancel = () => {
    $editId(null);
  };

  //点击回车，使输入框失去焦点
  const onInputEnter = (e: any) => {
    if (e.keyCode == '13') {
      e.currentTarget.blur()
    }
  }

  // 输入框失去焦点事件 编辑标签
  const onInputBlur = async (e: any, data: any) => {
    const val = e.target.value;
    if (val == '') {
      return message.error(getMessage('SearchEngine.updateError'))
    }
    $editId(null);
    await editLabelName({
      ...data,
      LabelName: val,
    }).then(() => {
      $tagList((list) => {
        const newList = [...list];
        const index = newList.findIndex((item) => item.Id == data.Id);
        newList[index] = {
          ...newList[index],
          LabelName: val,
        };
        message.success(getMessage('SearchEngine.updateSuccess'))
        return newList;
      });
    });
  };

  const onItemClick = useCallback(
    (item) => {
      onItemPress?.(item.Id, JSON.parse(item.LabelValue));
    },
    [onItemPress],
  );

  // const viewType = useViewType();
  return (
    <div className={cn('my-search-tag-container')}>
      <div className={cn(`tag-item-title`)}>
        <TextWidget>SearchEngine.mySearch</TextWidget>
      </div>
      <div className="tag-list">
        {tagList.map((item, index) => {
          return (
            <div className="tag-item" key={index}>
              {editId == item.Id && (
                <input
                  className={`tag-item-input`}
                  type="text"
                  defaultValue={item.LabelName}
                  autoFocus
                  onKeyDown={onInputEnter}
                  onBlur={(e) => onInputBlur(e, item)}
                />
              )}
              {editId != item.Id && (
                <span
                  onClick={(e) => {
                    e.stopPropagation();
                    onItemClick(item);
                  }}
                  className="tag-item-label"
                >
                  {item.LabelName}
                </span>
              )}
              {editId != item.Id && (
                <div className="tag-action-box">
                  <InbizIcon
                    type="icon-ic-bianjituandui"
                    className="tag-item-setting"
                    onClick={(e) => {
                      e.stopPropagation();
                      onEdit(item.Id);
                    }}
                  />
                  <Popconfirm
                    onConfirm={(e) => {
                      confirm(item);
                    }}
                    onCancel={cancel}
                    title={getMessage('SearchEngine.deleteSearchTag')}
                    okText={getMessage('SearchEngine.confirm')}
                    cancelText={getMessage('SearchEngine.cancel')}
                  >
                    <CloseOutlined className="tag-item-delete" />
                  </Popconfirm>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
});

export default MySearchTag;
